package com.crm.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.constant.JwtClaimsConstant;
import com.crm.common.constant.UserConstants;
import com.crm.common.exception.base.BaseException;
import com.crm.common.properties.JwtProperties;
import com.crm.common.utils.JwtUtils;
import com.crm.domain.User;
import com.crm.dto.UserLoginDto;
import com.crm.mapper.UserMapper;
import com.crm.service.CaptchaService;
import com.crm.service.UserService;
import com.sun.security.auth.UserPrincipal;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;

    private final JwtProperties jwtProperties;

    private final CaptchaService captchaService;

    private final RedisTemplate redisTemplate;

    @Override
    public String login(UserLoginDto dto) {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, dto.getUsername()));

        if (user == null) {
            throw new BaseException("账号不存在") ;
        }
        if (!dto.getPassword().equals(user.getPassword())) {
            throw new BaseException("密码错误") ;
        }
        if (user.getStatus() != UserConstants.NORMAL) {
            throw new BaseException("账号已停用") ;
        }

        // 验证码校验
        boolean flag = captchaService.validateCaptcha(dto.getUuid(), dto.getCode());
        if (!flag) {
            return "验证码错误";
        }

        // JWT 工具类生成 token
        String token = JwtUtils.generateToken(user.getUserId());

        return token;
    }

}


